package sury.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sury.biz.service.AdminService;
import sury.common.constant.MessageConstant;
import sury.dal.dto.AdminDTO;
import sury.dal.dto.AdminLoginDTO;
import sury.dal.entity.AdminEntity;
import sury.dal.entity.AdminRoleEntity;
import sury.dal.mapper.AdminMapper;
import sury.dal.mapper.AdminRoleMapper;

import java.util.List;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, AdminEntity> implements AdminService{

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Override
    public void saveAdmin(AdminDTO adminDTO) {
//        if(baseMapper.selectCount(new QueryWrapper<AdminEntity>().eq("name",adminDTO.getName()))>0
//                || baseMapper.selectCount(new QueryWrapper<AdminEntity>().eq("phone",adminDTO.getPhone()))>0){
//            throw new RuntimeException("Name or phone number already exists.");
//        }
        AdminEntity adminEntity= BeanUtil.copyProperties(adminDTO,AdminEntity.class);
        save(adminEntity);
    }

    @Override
    public Object pageAdmin(Page<AdminEntity> page, String name) {
        return page(page,new QueryWrapper<AdminEntity>().like(name!=null&&!name.isEmpty(),"name",name));
    }

    @Override
    public void updateById(Long id, AdminDTO adminDTO) {
        AdminEntity adminEntity= BeanUtil.copyProperties(adminDTO,AdminEntity.class);
        adminEntity.setId(id);
        updateById(adminEntity);
    }

    @Override
    public void assignRolesToUser(Long adminId, List<Long> roleIds) {
        //删除该用户的所有角色
        adminRoleMapper.delete(new QueryWrapper<AdminRoleEntity>().eq("admin_id",adminId));

        //添加新的角色
        for(Long roleId:roleIds){
            AdminRoleEntity adminRoleEntity=new AdminRoleEntity();
            adminRoleEntity.setAdminId(adminId);
            adminRoleEntity.setRoleId(roleId);
            adminRoleMapper.insert(adminRoleEntity);
        }
    }

    @Override
    public Object getRoleList(Long id) {
        return adminRoleMapper.selectList(new QueryWrapper<AdminRoleEntity>().eq("admin_id",id).select("role_id"));
    }

    @Override
    public AdminEntity adminLogin(AdminLoginDTO adminLoginDTO) {
        //检查账号密码
        AdminEntity adminEntity=baseMapper.selectOne(new QueryWrapper<AdminEntity>()
                .eq("phone",adminLoginDTO.getPhone())
                .eq("password", adminLoginDTO.getPassword()));
        if(adminEntity==null){throw new RuntimeException(MessageConstant.LOGIN_FAILED);}
        return adminEntity;
    }
}
